from flask import request
from flask_wtf import FlaskForm
from flask_wtf.file import FileAllowed, FileRequired
from wtforms import StringField,SubmitField,FileField
from wtforms.fields.choices import SelectField
from wtforms.validators import DataRequired

from models import User, to_binary, insert, Prove

IMG_ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif'}
IMG_ALLOWED_MESSAGE='只允许上传图片文件 (JPG, JPEG, PNG, GIF)'


# mutiple form need name button
class PersonalForm(FlaskForm):
    img = FileField('选择文件', validators=[
        FileAllowed(IMG_ALLOWED_EXTENSIONS, IMG_ALLOWED_MESSAGE)
    ])

    text = StringField('请输入文字')
    submit = SubmitField('上传')

class ProveForm(FlaskForm):
    img = FileField('选择文件', validators=[
        FileRequired(),
        FileAllowed(IMG_ALLOWED_EXTENSIONS,IMG_ALLOWED_MESSAGE)
    ])

    role = SelectField('选择一个选项', choices=[
        ('', '请选择'),
        ('学生', '学生'),
        ('教师', '教师'),
        ('职工', '职工')
    ], validators=[DataRequired(message='必须选择一个选项')])

    submit = SubmitField('上传')

# submit1 is the name of button
def is_personal(form:PersonalForm):
    return form.validate_on_submit() and 'submit1' in request.form

def is_prove(form:ProveForm):
    return form.validate_on_submit() and 'submit2' in request.form


def submit_personal(form:PersonalForm,uid):
    if is_personal(form):
        user = User.get_by_uid(uid)
        if form.img.data:
           user.img = to_binary(form.img.data)
        if form.text.data :
           user.text = form.text.data
        insert(user)
        return True
    return False

def submit_prove(form:ProveForm,uid):
    if is_prove(form):
        row = Prove.get_by_uid(uid)
        row.status=0
        if form.img.data:
            row.img = to_binary(form.img.data)
        row.role = form.role.data
        insert(row)
        return True
    return False


